package com.crm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.base.ResponseResult;
import com.crm.domain.dto.QueryCourse;
import com.crm.domain.entity.Course;
import com.crm.service.ICourseService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/clues/course")
public class CourseController {

    private final ICourseService courseService;
    /**
     * 根据subject查询
     */
    @GetMapping("listselect")
    public ResponseResult getByDictType(Integer subject) {
        if (subject != null) {
            List<Course> list = courseService.lambdaQuery().eq(Course::getSubject, subject).list();
            return ResponseResult.success(list);
        }else {
            return ResponseResult.success(courseService.lambdaQuery().list());
        }
    }

    /**
     * 分页查询
     * @param queryCourse
     * @return
     */
    @GetMapping("/list")
    public ResponseResult queryAll(QueryCourse queryCourse){
        Page<Course> page = courseService.queryAll(queryCourse);
        return ResponseResult.success()
                .put("rows", page.getRecords())
                .put("total", page.getTotal());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseResult getById(@PathVariable Integer id){
        Course course = courseService.getById(id);
        return ResponseResult.success(course);
    }

    /**
     * 新增
     * @param course
     * @return
     */
    @PostMapping
    public ResponseResult save(@RequestBody Course course){
        //生成随机数 课程编号
        String random = RandomStringUtils.random(8, true, true);
        course.setCode(random);
        courseService.save(course);
        return ResponseResult.success();
    }

    /**
     * 修改
     * @param course
     * @return
     */
    @PutMapping
    public ResponseResult update(@RequestBody Course course){
        courseService.lambdaUpdate().eq(Course::getId, course.getId()).update(course);
        return ResponseResult.success();
    }

    /**
     * 根据Id删除
     * @param ids
     * @return
     */
    @DeleteMapping("{ids}")
    public ResponseResult deleteById(@PathVariable List<Long> ids){
        ids.forEach(id ->{courseService.lambdaUpdate().eq(Course::getId, id).remove();});
        return ResponseResult.success();
    }
}
